using System.Collections.Generic;
using System.Net.Http.Headers;

namespace Web_rongmeiti_sys.PublishToRongMeiTi
{
    /// <summary>
    /// 获取文章信息
    /// </summary>
    /// 创建时间：2023-5-31 15:10:51。作者：王浩力
    public class GetArticleInfoHandler
    {
        /// <summary>
        /// 超时时间，单位秒；
        /// </summary>
        const int SendTimeOutSeconds = 10;

        /// <summary>
        /// 根据标题、栏目id、文章id查询在甲甲中的文章数据id，Url
        /// </summary>
        /// <param name="title">文章标题</param>
        /// <param name="dataId">原业务系统的文章id</param>
        /// <param name="columnID">甲甲的栏目id</param>
        /// <param name="cnpc_account">发布信息人的cnpc_account账号</param>
        /// <param name="cnpcPassword">发布信息人账号密码</param>
        /// <param name="publishDate">发布日期</param>
        /// 创建时间：2023-7-31 11:04:35，作者：王浩力
        public static async Task<Result<PageItemInfo>> GetRongMeiTiArticleInfo(string title, string columnID, string dataId, string cnpc_account, string cnpcPassword, DateTime publishDate, int pageIndex = 1)
        {
            Result<PageItemInfo> result = new Result<PageItemInfo>() { Code = 500 };
            if (string.IsNullOrWhiteSpace(cnpc_account))
            {
                result.Msg = "参数cnpc_account不可为空";
                return result;
            }
            if (string.IsNullOrWhiteSpace(cnpcPassword))
            {
                result.Msg = "参数cnpcPassword不可为空";
                return result;
            }
            if (string.IsNullOrWhiteSpace(columnID))
            {
                result.Msg = "参数columnID不可为空";
                return result;
            }
            if (string.IsNullOrWhiteSpace(dataId))
            {
                result.Msg = "参数dataId不可为空";
                return result;
            }
        Get_user_info:
            GetCurrentUserInfo publishUser = ArticlePublishHandler.GetUserInfo(cnpc_account);
            if (publishUser == null || publishUser.result == null)
            {
                //result.Msg = "发布人信息没有获取到，请检查";
                //return result;

                //重新登录，获取身份信息，获取cookie的值
                LoginHandler.LoginCall(cnpc_account, cnpcPassword);
                goto Get_user_info;
            }
            ushort errorCount = 0;

        Again_publish:
            HttpClient httpClient = new HttpClient();
            httpClient.Timeout = TimeSpan.FromSeconds(SendTimeOutSeconds);

            //获取身份信息，获取cookie的值
            string? identityCookie = AuthCookieHelpter.GetIdentityCookie(cnpc_account);
            if (string.IsNullOrWhiteSpace(identityCookie))
            {
                if (errorCount >= 4)
                {
                    result.Msg = "登录失败";
                    return result;
                }
                //重新登录，获取身份信息，获取cookie的值
                LoginHandler.LoginCall(cnpc_account, cnpcPassword);
                errorCount++;
                goto Again_publish;
            }
            //LogHelpter.AddLog($"文章id={article.ArticleId},收到的文章RedirectURL={article.RedirectURL}", null, "RedirectURL");

            httpClient.DefaultRequestHeaders.Add("Userselectorgcode", publishUser.result.orgCode);
            httpClient.DefaultRequestHeaders.Add("Cookie", identityCookie);

            /*
             https://xxx.xx.com/api/News_PCN/GetPaged?columnID=18c0af3a-9054-4ba9-270e-08db8f340d4a&SearchType=1&pageIndex=1&pageSize=30&tableType=issue
             */
            string url = MyConfigReader.GetConfigValue("pf_eip_GetPaged_url")
                + columnID + $"&SearchType=1&pageIndex={pageIndex}&pageSize=30&tableType=issue";

            HttpResponseMessage responseMessage = await httpClient.GetAsync(url);
            string resultJson = await responseMessage.Content.ReadAsStringAsync();
            LogHelpter.AddLog($"获取文章信息,栏目id={columnID},dataId={dataId}，甲甲返回：" + resultJson, null, "GetArticleInfoHandler");

            if (responseMessage.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                //错误次数累计
                errorCount++;
                if (errorCount > 2)
                {
                    result.Msg = "甲甲报401，没有获取到身份信息";
                    return result;
                }

                //重新登录，获取身份信息，获取cookie的值
                var loginResult = LoginHandler.LoginCall(cnpc_account, cnpcPassword);
                if (loginResult.Code != 200)
                {
                    result.Msg = loginResult.Msg;
                    return result;
                }

                goto Again_publish;
            }
            bool right = responseMessage.StatusCode == System.Net.HttpStatusCode.OK;
            if (right)
            {
                ResultGetPage resultPage = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultGetPage>(resultJson);
                if (resultPage.code != 200)
                {
                    result.Msg = resultPage.message;
                    return result;
                }
                ////文章发布成功，通知
                //PublishArticleSuccessed?.Invoke(null, article);
                if (resultPage.result.rowsCount == 0)
                {
                    result.Msg = "没有数据";
                    return result;
                }

                var date = publishDate.Date;/* 发布日期 */
                string fileName = dataId + ".aspx";/* pageUrl文件名  */
                var findOne = resultPage.result.listEntity.Where(g =>
                     //g.publishingDate.Value == date
                     //g.createTime.Value.Date == date && 
                     g.pageUrl.EndsWith(fileName)
                   ).FirstOrDefault();

                result.Code = 200;
                result.Data = findOne;
                return result;
            }

            result.Msg = "获取失败";
            return result;
        }

    }
}
